package com.lethe.medical.action.sys;

import com.lethe.medical.base.BaseServlet;
import com.lethe.medical.base.annotation.MethodAnnotation;
import com.lethe.medical.entity.UserEntity;
import com.lethe.medical.service.UserService;
import com.lethe.medical.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    private UserService userService = new UserServiceImpl();

    /**
     * 登录方法
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @MethodAnnotation(method="login.action")
    public void login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        //System.out.println("login方法");
        boolean flag = false;//成功标志
        HttpSession session = request.getSession();//获取session
        UserEntity u = super.requestToBean(request, UserEntity.class);

        System.out.println(u.getUsername());
        UserEntity userEntity = userService.login(u);
        //判断登录
        if(userEntity !=null) {
            //登录成功
            session.setAttribute("userEntity", userEntity);
            request.setAttribute("userEntity", userEntity);
            super.dispatcher(request,response,"index");
        }else {
            //登录失败，重定向
            super.sendRedirect(request,response,"index");

        }
    }

    /**
     * 添加用户
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @MethodAnnotation(method="add")
    public void add(HttpServletRequest request, HttpServletResponse response)throws ServletException , IOException{
        UserEntity userEntity = super.requestToBean(request, UserEntity.class);
        System.out.println("add方法执行了");
        System.out.println(userEntity.getUsername());
        userService.save(UserEntity.class, userEntity);

    }

    @MethodAnnotation(method="update")
    public void update(HttpServletRequest request, HttpServletResponse response)throws ServletException , IOException{
        UserEntity userEntity = super.requestToBean(request, UserEntity.class);
        System.out.println("add方法执行了");
        System.out.println(userEntity.getUsername());
        userService.update(UserEntity.class, userEntity);

    }


}
